package com.schedule.server.serverImpl;
import com.schedule.dto.LoginDto;
import com.schedule.entity.LoginUser;
import com.schedule.exception.AccountNotFoundException;
import com.schedule.exception.MessageConstant;
import com.schedule.mapper.AdminMapper;
import com.schedule.server.AdminServer;
import com.schedule.utils.SaltUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminServerImpl implements AdminServer {

    @Autowired
    private AdminMapper adminMapper;

    /**
    * 用户登录逻辑，校验用户名和密码
     * @param loginDto 登录参数
     * @return 登录用户信息

     */
    public LoginUser Login(LoginDto loginDto)  {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        LoginUser loginUserDate= adminMapper.Login(username);

        if (loginUserDate == null){
            throw  new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        String User_salt = loginUserDate.getSalt();
        if(!SaltUtil.verifyPassword(password,User_salt, loginUserDate.getPassword())){
            throw  new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);
        }
        return loginUserDate;
    }

    /**
     * 注册
     * @param registerData 注册参数
     * @return 注册信息
     */
    public void Regiser(LoginDto registerData) {

        String salt = SaltUtil.createSalt();
        registerData.setPassword(SaltUtil.hashPassword(registerData.getPassword(),salt));

        LoginUser registerObj = new LoginUser();
        BeanUtils.copyProperties(registerData,registerObj);
        registerObj.setSalt(salt);
        registerObj.setRole(0);
        adminMapper.Register(registerObj);
    }



}
